<template>
  <h4>{{ title }}</h4>
  <canvas :id="key" class="c2d" width="1000" height="500"></canvas>
</template>

<script setup>
import { ref, onMounted } from "vue";
import * as THREE from "three";

const key = ref("c2d" + Math.floor(Math.random() * 10000));
const props = defineProps({
  title: String,
});

onMounted(() => {
  const canvas = document.querySelector(`#${key.value}`);

  const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });

  // 1. 创建一个场景
  const scene = new THREE.Scene();

  {
    // 方向光1
    const color = 0xffffff;
    const intensity = 1;
    const light = new THREE.DirectionalLight(color, intensity);
    light.position.set(40, 40, 50);
    scene.add(light);
  }

  {
    // 方向光2
    const light = new THREE.DirectionalLight(0xffffff, 1);
    light.position.set(-10, -5, -30);
    scene.add(light);
  }

  // 创建物体
  var geometry = new THREE.BoxGeometry();
  var material = new THREE.MeshPhongMaterial({ color: 0x6688aa });
  var object = new THREE.Mesh(geometry, material);
  // 将物体添加到场景中
  scene.add(object);

  // 透视投影相机
  const fov = 40; // 视野范围
  const aspect = 2; // 相机默认值 画布的宽高比
  const near = 0.1; // 近平面
  const far = 1000; // 远平面
  const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  // 设置相机 x、y、z 位置
  camera.position.set(0, 50, 0);
  // 相机指向的场景中心
  camera.lookAt(0, 0, 0);

  // 底部网格（可以不设置）
  const gridHelper = new THREE.GridHelper(300, 25, 0x004444, 0x004444);
  scene.add(gridHelper);

  // 设置物体的初始位置和速度
  const objectPosition = new THREE.Vector3(0, 0, 0);
  const objectVelocity = new THREE.Vector3(0, 0, -0.5); // 沿着x轴移动

  // 帧循环中更新物体位置
  function animateObject() {
    // 让物体沿着固定路径移动
    objectPosition.add(objectVelocity);

    // 更新物体的位置
    object.position.copy(objectPosition);

    // 当物体到达一定位置后，重置到起始位置
    if (objectPosition.z < -150) {
      objectPosition.z = 0;
    }
    renderer.render(scene, camera);
    // 请求下一帧动画
    requestAnimationFrame(animateObject);
  }
  animateObject();

  // 帧循环中更新相机位置
  function animateCamera() {
    requestAnimationFrame(animateCamera);

    // 将相机位置设置为物体的位置，并根据需要添加偏移量
    var offset = new THREE.Vector3(0, 5, 20); // 示例偏移量
    camera.position.copy(object.position).add(offset);

    // 设置相机的朝向，让其始终看向物体
    camera.lookAt(object.position);

    renderer.render(scene, camera);
  }

  animateCamera();
});
</script>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>
